package logic

import (
	"core/command"
	"core/common"
	"core/component/logger"
	"core/helper/util"
	"core/logic/logicredis"
)

// 开始匹配
func (player *Player) startPvpHandler(msgId uint16, data []byte) {
	msgRecv := &command.CSStartPvp{}
	err := player.router.UnMarshal(data, msgRecv)
	if err != nil {
		logger.Errorf("recv data:%v msg:%v", data, msgRecv)
		return
	}
	player.sendMsgToPvp(command.Command(msgId), msgRecv)
}

// 出牌
func (player *Player) outOfCardsHandler(msgId uint16, data []byte) {
	msgRecv := &command.CSOutOfCardsPvp{}
	err := player.router.UnMarshal(data, msgRecv)
	if err != nil {
		logger.Errorf("recv data:%v msg:%v", data, msgRecv)
		return
	}
	msgRecv.PlayerId = player.playerId

	player.sendMsgToPvp(command.Command(msgId), msgRecv)
}

// 取消匹配
func (player *Player) cancelHandler(msgId uint16, data []byte) {
	msgRecv := &command.CSCancelPvp{}
	err := player.router.UnMarshal(data, msgRecv)
	if err != nil {
		logger.Errorf("recv data:%v msg:%v", data, msgRecv)
		return
	}
	msgRecv.PlayerId = player.playerId
	player.sendMsgToPvp(command.Command(msgId), msgRecv)
}

// 设置玩家名字
func (player *Player) setNickNameHandler(msgId uint16, data []byte) {
	msgRecv := &command.CSSetNickName{}
	err := player.router.UnMarshal(data, msgRecv)
	if err != nil {
		logger.Errorf("recv data:%v msg:%v", data, msgRecv)
		return
	}
	msgSend := &command.SCSetNickName{}
	if logicredis.CacheRedis().Exists(common.MakeNickNameKey(msgRecv.NickName)).Val() == 0 &&
		msgRecv.NickName != "" && len(msgRecv.NickName) <= 21 {
		player.user.setNickName(msgRecv.NickName)
		msgSend.NickName = msgRecv.NickName
		msgSend.Result = true
	}
	player.playerIntoPvp()
	player.sendMsg(command.Command_SCSetNickName_Online, msgSend)
}

func (player *Player) randNickNameHandler(msgId uint16, data []byte) {
	msgRecv := &command.CSRandNickName{}
	err := player.router.UnMarshal(data, msgRecv)
	if err != nil {
		logger.Errorf("recv data:%v msg:%v", data, msgRecv)
		return
	}
	msgSend := &command.SCRandNickName{}
	defer player.sendMsg(command.Command_SCRandNickName_Online, msgSend)
	if player.user.nickName != "" {
		return
	}
	msgSend.Name = util.NameMgrGetMe().RandName()
}

// 聊天
func (player *Player) chatMsgHandler(msgId uint16, data []byte) {
	msgRecv := &command.CSChatMsg{}
	err := player.router.UnMarshal(data, msgRecv)
	if err != nil {
		logger.Errorf("recv data:%v msg:%v", data, msgRecv)
		return
	}
	msgRecv.PlayerId = player.playerId
	player.sendMsgToPvp(command.Command(msgId), msgRecv)
}
